// index.js
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    goodsDetail: {},
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "",
    selectSizePrice: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 0,
    buyNumMin: 0,
    buyNumMax: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    favorite:false,
    CurrentPid:0,
    isAccredit: false
  },
  //事件处理函数
  swiperchange: function (e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    let that = this;
    let isAccredit = util.isAccredit(function (isAccredit) {
      that.setData({
        isAccredit: isAccredit
      })
    });
    that.setData({ CurrentPid:e.id});
    
  },
  tokefu:function(){
    wx.reLaunch({
      url: '/pages/kefu/index',
    })
  },
  //是否授权登陆
  toShowToast: function () {
    let that = this;
    let back = '/pages/goods-details/index'
    wx.showModal({
      title: '提示',
      content: '登陆之后即可预约，是否确认登陆',
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '../accredit/index?back=' + back + '&id=' + that.data.CurrentPid,
          })
        }
      }
    })
  },

  //分享
  onShareAppMessage: function () {
    return {
      title: this.data.goodsDetail.ProductInfo.Name,
      path: this.data.pathGoods,
      success: function (res) {
        // 转发
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  //分销
  GetSharePagePath: function () {
    var that = this;
    var disId = wx.getStorageSync('disid')
    var agentId = wx.getStorageSync('agentid')
    if (!disId) {
      disId = 0
    }
    if (!agentId) {
      agentId = 0
    }
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate',
      data: {
        userId: app.globalData.userInfo.Uid,
        storeId: app.globalData.storeId,
        agentId: agentId,
        disId: disId,
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var path = '';
          if (res.data.Data.IsAgent == 0) {
            path = "/pages/goods-details/index?disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId + "&id=" + that.data.CurrentPid
          } else {
            path = "/pages/goods-details/index?disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId + "&id=" + that.data.CurrentPid
          }
          that.setData({
            pathGoods: path
          })
        }
      }
    })
  },
  //清空购物车
  clearShopCar: function (pid, name, shopprice) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Cart/Clear',
      data: {
        uid: app.globalData.userInfo.Uid,
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.addShopCar(pid, name, shopprice);//加入购物车
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //加入购物车
  addShopCar: function (pid, name, shopprice) {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/cart/AddProduct',
      data: {
        uid: app.globalData.userInfo.Uid,
        pid: pid,
        buyCount: 1
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          that.setData({
            shopNum: res.data.Data//购物车数量
          });
          wx.navigateTo({
            url: '/pages/yuyue/index?pid=' + pid + "&doctor=" + name + "&shopprice=" + shopprice,
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
 
  // subscribe预约
  subscribe:function(e){
    wx.showLoading({
      title: '提交中...',
    })
    var name = this.data.goodsDetail.ProductInfo.Name;
    var pid = this.data.CurrentPid;
    var shopprice = this.data.selectSizePrice;
    this.clearShopCar(pid, name, shopprice);
  },
  numJianTap: function () {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function () {
    if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    }
  },

  favorite:function(e){
    var that=this;
    var pid = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.host + '/api/user/ProductFavorite',
      data: {
        pid: pid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if(res.data.Code==0){
          var oldF = that.data.favorite;
          if(oldF){
            wx.showModal({
              title: '取消收藏成功',
              content: '',
              showCancel:false
            })
          }else{
            wx.showModal({
              title: '收藏成功',
              content: '',
              showCancel: false
            })
          }
          that.setData({ favorite: !oldF })
        }
        
      }
    })
  },
  initPage:function(){
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    // 获取购物车数据
    wx.request({
      url: app.globalData.host + '/api/cart/index',
      data: {
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({ shopNum: res.data.Data.TotalCount })
        }

      }
    })
    
    wx.request({
      url: app.globalData.host + '/api/user/CheckProductFavorite',
      data: {
        pid: that.data.CurrentPid,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        var f = res.data.Data;
        that.setData({ favorite: f })
      }
    })
    wx.request({
      url: app.globalData.host + '/api/store/Product',
      data: {
        pid: that.data.CurrentPid
      },
      success: function (res) {
        wx.hideLoading()
        var p = res.data.Data;
        if (!p.ProductInfo || p.ProductInfo.State != 0) {
          wx.showModal({
            title: '商品已下架',
            content: '',
            showCancel: false
          })
          return;
        }
        if (p.ProductInfo.ShowImg) {
          p.ProductInfo.ShowImg = app.globalData.image800_800host + p.ProductInfo.ShowImg;
        }
        for (var i = 0; i < p.ProductImageList.length; i++) {
          p.ProductImageList[i].ShowImg = app.globalData.image800_800host + p.ProductImageList[i].ShowImg;
        }
        if (p.ExtGiftList){
          for (var i = 0; i < p.ExtGiftList.length; i++) {
            p.ExtGiftList[i].ShowImg = app.globalData.image190_190host + p.ExtGiftList[i].ShowImg;
          }
        }
        
        var selectSizeTemp = "";
        var pnames = "";
        if (p.CurrProductSkuList.length > 0) {
          for (var i = 0; i < p.CurrProductSkuList.length; i++) {
            pnames += p.CurrProductSkuList[i].AttrName + ":";
            var value = p.CurrProductSkuList[i].AttrValue;
            if (p.CurrProductSkuList[i].IsInput) {
              value = p.CurrProductSkuList[i].InputValue;
            }
            selectSizeTemp = selectSizeTemp + " " + value;
            pnames += value + " "
          }
          that.setData({
            hasMoreSelect: true,
            selectSize: that.data.selectSize + selectSizeTemp,
            selectSizePrice: p.ProductInfo.ShopPrice,
            propertyChildNames: pnames
          });
        }
        that.setData({
          goodsDetail: p,
          selectSizePrice: p.ProductInfo.ShopPrice,
          buyNumMax: p.StockNumber,
          buyNumber: (p.StockNumber > 0) ? 1 : 0
        });
        WxParse.wxParse('article', 'html', p.ProductInfo.Description, that, 5);
      }
    })
    that.pingjiaList(that.data.CurrentPid);
  },
  selectGoods: function (e) {
    console.log("点击商品评价")
    wx.navigateTo({
      url: '/pages/pingjia-list/index?pid=' + this.data.CurrentPid
    })
  },
  //获取评价列表
  pingjiaList: function (pid) {
    var that = this;
    var postDatalist = {
      uid: app.globalData.userInfo.Uid,
      page: 1
    };
    wx.request({
      url: app.globalData.host + '/api/store/productreviewlist?pid=' + pid + '&page=1',
      success: (res) => {
        var ReviewListTwo = [];
        that.setData({
          ReviewListLength: res.data.Data.ProductReviewList.length
        })
      }
    })
  },
  // 弹出层
  showModal2: function (e) {
    var mallName = wx.getStorageSync("mallName")
    this.getWxaCode()
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.setData({
      animationData2: animation.export(),
      showModalStatus2: true,
      mallName: mallName
    })
    setTimeout(function () {
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal2: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    this.setData({
      animationData2: animation.export(),
    })
    setTimeout(function () {
      this.setData({
        animationData2: animation.export(),
        showModalStatus2: false
      })
    }.bind(this), 200)
  },
  //获取商品二维码
  getWxaCode: function () {
    var that = this
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: that.data.pathGoods,
        storeappid: app.globalData.storeAppId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            that.setData({
              productCode: 'http://static.711688.net.cn/upload/user/' + res.data.Data
            })
          }
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      that.initPage();
      that.GetSharePagePath()
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 页面相关事件处理函数--监听用户下拉动作
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})